package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.context.SessionConstants;
import cn.livingCloud.dto.CaseCommentFormDto;
import cn.livingCloud.entity.core.CaseComments;
import cn.livingCloud.entity.core.Employee;
import cn.livingCloud.entity.user.Member;
import cn.livingCloud.entity.user.User;
import cn.livingCloud.repository.CaseCommentsMapper;
import cn.livingCloud.service.WxTemplateMsgService;
import cn.livingCloud.utils.SessionUtils;
import org.apache.commons.lang.StringUtils;

/**
 * 创建案件评论
 * Created by 唐旭 on 2016/6/14.
 */
public class CaseCommentCreator {

    private transient CaseCommentsMapper commentsMapper = BeanProvider.getBean(CaseCommentsMapper.class);
    private transient WxTemplateMsgService templateMsgService = BeanProvider.getBean(WxTemplateMsgService.class);
    private CaseCommentFormDto formDto;

    public CaseCommentCreator(CaseCommentFormDto formDto) {
        this.formDto = formDto;
    }

    public CaseComments create() {
        CaseComments comments = new CaseComments();
        comments.setCaseUuid(formDto.getCaseUuid())
                .setContent(formDto.getContent());

        setCreator(comments);
        commentsMapper.insert(comments);

        //如果是给member(用户)留言,则发送模板消息提醒
        sendCommentsTips(comments);
        return comments;
    }

    private void sendCommentsTips(final CaseComments comments) {
        String memberUuid = comments.getMemberUuid();
        if (StringUtils.isNotEmpty(memberUuid)) {
            return;
        }

        templateMsgService.sendTemplate(comments);
    }

    /**
     * 设置评论创建人
     * 1,评论优先级为 User -> Employee -> Member
     *
     * @param comments 需要设置创建人的评论对象
     */
    private void setCreator(CaseComments comments) {
        User currentUser = (User) SessionUtils.getCurrentUser();
        if (currentUser != null) {
            comments.setUserUuid(currentUser.getUuid());
            return;
        }
        Employee employee = SessionUtils.getAttribute(Employee.class, SessionConstants.EMPLOYEE_KEY);
        if (employee != null) {
            comments.setEmployeeUuid(employee.getUuid());
            return;
        }
        Member member = (Member) SessionUtils.getCurrentMember();
        if (member != null) {
            comments.setMemberUuid(member.getUuid());
        }
    }
}
